package com.bzsg.simpleMediaPlayer.ui.pager
import android.Manifest
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.Settings
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.PermissionStatus
import com.google.accompanist.permissions.rememberPermissionState
import com.google.accompanist.permissions.shouldShowRationale

@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun PermissionRequest() {
    val context = LocalContext.current
    val prefs = remember { context.getSharedPreferences("PermissionPrefs", Context.MODE_PRIVATE) }
    var request by remember {
        mutableStateOf(prefs.getBoolean("request", false))
    }

    val permissionState = rememberPermissionState(Manifest.permission.READ_MEDIA_VIDEO)
    // 进入时自动检测并请求权限
    val permissionLauncher =
        rememberLauncherForActivityResult(
            ActivityResultContracts.RequestPermission(),
        ) { isGranted ->
            // 如果永久允许或者拒绝，不会再弹窗
            if (permissionState.status.shouldShowRationale || !isGranted) {
                request = true
                prefs.edit().putBoolean("request", true).apply()
            }
        }
    LaunchedEffect(Unit) {
        if (permissionState.status != PermissionStatus.Granted && !permissionState.status.shouldShowRationale) {
            permissionLauncher.launch(Manifest.permission.READ_MEDIA_VIDEO)
        }
    }

    // 界面控制逻辑
    when {
        permissionState.status == PermissionStatus.Granted -> {
            // MediaContentScreen() // 主界面
            Text("loaded")
        }
        // 请求权限弹窗过程中界面
        !request -> {
            // 请求界面
            Text("loading")
        }
        else -> {
            PermanentDenialScreen(
                onOpenSettings = {
                    val intent =
                        Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                            data = Uri.fromParts("package", context.packageName, null)
                        }
                    context.startActivity(intent)
                },
            )
        }
    }
}

// 永久拒绝引导界面
@Composable
fun PermanentDenialScreen(onOpenSettings: () -> Unit) {
    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        Icon(
            imageVector = Icons.Default.Settings,
            contentDescription = "设置",
            modifier = Modifier.size(64.dp),
            tint = MaterialTheme.colorScheme.onError,
        )

        Spacer(modifier = Modifier.height(24.dp))

        Text(
            "您已永久拒绝权限",
            style = MaterialTheme.typography.bodyMedium,
            textAlign = TextAlign.Center,
        )

        Spacer(modifier = Modifier.height(8.dp))

        Text(
            "请在系统设置中手动启用权限",
            style = MaterialTheme.typography.bodyMedium,
            textAlign = TextAlign.Center,
        )

        Spacer(modifier = Modifier.height(24.dp))

        Button(onClick = onOpenSettings) {
            Text("打开系统设置")
        }
    }
}
